//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package test;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class CommunityForum {
    private JFrame forumFrame;
    private DefaultTableModel postModel;
    private JTable postTable;

    public CommunityForum() {
        this.initializeDatabase();
        this.forumFrame = new JFrame("社区论坛");
        this.forumFrame.setSize(800, 600);
        this.forumFrame.setLocationRelativeTo((Component)null);
        this.forumFrame.setDefaultCloseOperation(2);
        String[] columns = new String[]{"标题", "作者", "发布时间", "浏览数", "回复数"};
        this.postModel = new DefaultTableModel(columns, 0);
        this.postTable = new JTable(this.postModel);
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton newPostBtn = new JButton("发新帖");
        JButton viewPostBtn = new JButton("查看帖子");
        JButton refreshBtn = new JButton("刷新");
        JButton backBtn = new JButton("返回主菜单");
        Font btnFont = new Font("SimSun", 0, 14);
        newPostBtn.setFont(btnFont);
        viewPostBtn.setFont(btnFont);
        refreshBtn.setFont(btnFont);
        backBtn.setFont(btnFont);
        this.loadPostsFromDatabase();
        newPostBtn.addActionListener((e) -> this.showPostDialog());
        viewPostBtn.addActionListener((e) -> this.showPostDetails());
        refreshBtn.addActionListener((e) -> {
            this.refreshPostList();
            JOptionPane.showMessageDialog(this.forumFrame, "帖子列表已刷新");
        });
        backBtn.addActionListener((e) -> {
            this.forumFrame.dispose();
            (new Menu(null)).setVisible(true);
        });
        buttonPanel.add(newPostBtn);
        buttonPanel.add(viewPostBtn);
        buttonPanel.add(refreshBtn);
        buttonPanel.add(backBtn);
        this.forumFrame.add(new JScrollPane(this.postTable), "Center");
        this.forumFrame.add(buttonPanel, "South");
    }

    private void initializeDatabase() {
        String sql = "CREATE TABLE IF NOT EXISTS community_posts (id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255) NOT NULL,author VARCHAR(100) NOT NULL,post_time DATETIME NOT NULL,views INT DEFAULT 0,replies INT DEFAULT 0,content TEXT,UNIQUE KEY title_author (title, author)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
        ) {
            stmt.execute(sql);
        } catch (SQLException e) {
            this.showErrorDialog("数据库初始化失败", e);
        }

    }

    private void showPostDialog() {
        JDialog postDialog = new JDialog(this.forumFrame, "发表新帖", true);
        postDialog.setSize(500, 400);
        postDialog.setLocationRelativeTo(this.forumFrame);
        JTextField titleField = new JTextField();
        JTextArea contentField = new JTextArea();
        JButton submitBtn = new JButton("发布");
        submitBtn.setFont(new Font("SimSun", 0, 14));
        submitBtn.addActionListener((ev) -> {
            String title = titleField.getText().trim();
            String content = contentField.getText().trim();
            if (title.isEmpty()) {
                JOptionPane.showMessageDialog(postDialog, "标题不能为空", "输入错误", 2);
            } else {
                try {
                    if (this.addPostToDatabase(title, "当前用户", content)) {
                        this.postModel.addRow(new Object[]{title, "当前用户", new Date(), 0, 0});
                        JOptionPane.showMessageDialog(postDialog, "发帖成功!");
                        postDialog.dispose();
                    } else {
                        JOptionPane.showMessageDialog(postDialog, "发帖失败，可能是标题已存在", "错误", 0);
                    }
                } catch (SQLException e) {
                    this.showErrorDialog("发帖失败", e);
                }

            }
        });
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.add(new JLabel("标题:"), "West");
        titlePanel.add(titleField, "Center");
        panel.add(titlePanel, "North");
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.add(new JLabel("内容:"), "North");
        contentField.setLineWrap(true);
        contentField.setWrapStyleWord(true);
        contentPanel.add(new JScrollPane(contentField), "Center");
        panel.add(contentPanel, "Center");
        panel.add(submitBtn, "South");
        postDialog.add(panel);
        postDialog.setVisible(true);
        titleField.requestFocusInWindow();
    }

    private void showPostDetails() {
        int selectedRow = this.postTable.getSelectedRow();
        if (selectedRow >= 0) {
            String title = (String)this.postModel.getValueAt(selectedRow, 0);

            try {
                String content = this.getPostContent(title);
                if (content != null) {
                    JDialog viewDialog = new JDialog(this.forumFrame, "帖子详情: " + title, true);
                    viewDialog.setSize(600, 400);
                    viewDialog.setLocationRelativeTo(this.forumFrame);
                    JTextArea contentArea = new JTextArea(content);
                    contentArea.setEditable(false);
                    contentArea.setLineWrap(true);
                    contentArea.setWrapStyleWord(true);
                    viewDialog.add(new JScrollPane(contentArea));
                    viewDialog.setVisible(true);
                }
            } catch (SQLException e) {
                this.showErrorDialog("获取帖子内容失败", e);
            }
        } else {
            JOptionPane.showMessageDialog(this.forumFrame, "请先选择要查看的帖子", "提示", 2);
        }

    }

    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/community_db?" +
                "useSSL=false&" +
                "serverTimezone=UTC&" + // 推荐使用 UTC 避免时区问题
                "autoReconnect=true&" +
                "maxReconnects=10&" +
                "allowPublicKeyRetrieval=true"; // ✅ 允许公钥检索
        String user = "root";
        String password = "Ht20041228";
        return DriverManager.getConnection(url, user, password);
    }

    private void loadPostsFromDatabase() {
        String sql = "SELECT title, author, post_time, views, replies FROM community_posts ORDER BY post_time DESC";

        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
        ) {
            this.postModel.setRowCount(0);

            while(rs.next()) {
                this.postModel.addRow(new Object[]{rs.getString("title"), rs.getString("author"), rs.getTimestamp("post_time"), rs.getInt("views"), rs.getInt("replies")});
            }
        } catch (SQLException e) {
            this.showErrorDialog("加载帖子失败", e);
        }

    }

    private boolean addPostToDatabase(String title, String author, String content) throws SQLException {
        String sql = "INSERT INTO community_posts (title, author, post_time, views, replies, content) VALUES (?, ?, ?, ?, ?, ?)";

        boolean var7;
        try (
                Connection conn = this.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
        ) {
            pstmt.setString(1, title);
            pstmt.setString(2, author);
            pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
            pstmt.setInt(4, 0);
            pstmt.setInt(5, 0);
            pstmt.setString(6, content);
            var7 = pstmt.executeUpdate() > 0;
        }

        return var7;
    }

    private String getPostContent(String title) throws SQLException {
        String sql = "SELECT content FROM community_posts WHERE title = ?";

        try (Connection conn = this.getConnection()) {
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, title);
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    String var6 = rs.getString("content");
                    return var6;
                }
            }
        }

        return null;
    }

    private void refreshPostList() {
        this.postModel.setRowCount(0);
        this.loadPostsFromDatabase();
    }

    private void showErrorDialog(String title, Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(this.forumFrame, title + ": " + e.getMessage(), "错误", 0);
    }

    public void show() {
        this.forumFrame.setVisible(true);
    }
}
